﻿
using System.Collections.Generic;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Store;
namespace sharpxbot.Plugins.BibleSearch.FuzzySearch
{
    public class FullTextHelper
    {
        private const string SearchField = "text";

        public FullTextHelper(string pluginPath)
        {
            index = FSDirectory.GetDirectory(pluginPath + "LuceneIndex", false);
            analyzer = new StandardAnalyzer();
            searcher = new IndexSearcher(index);
            parser = new QueryParser(SearchField, analyzer);
        }

        public List<DocumentContainer> ExecuteSearch(string queryStr, int maxResults)
        {
            List<DocumentContainer> matches = ExecuteSearchImpl(queryStr, maxResults);
            return matches;
        }

        private List<DocumentContainer> ExecuteSearchImpl(string queryStr, int maxResults)
        {
            List<DocumentContainer> result = new List<DocumentContainer>();

            try
            {
                Query query = parser.Parse(queryStr);
                Hits hits = searcher.Search(query);

                int results = hits.Length();

                int currentResult = 0;

                for (int i = 0; i < results; i++)
                {
                    if (currentResult > maxResults - 1)
                        break;

                    DocumentContainer c = new DocumentContainer()
                    {
                        Document = hits.Doc(i),
                        Relevantity = hits.Score(i)
                    };

                    result.Add(c);

                    ++currentResult;
                }
            }
            catch { }

            return result;
        }

        private Directory index;
        private Analyzer analyzer;
        private IndexSearcher searcher;
        private QueryParser parser;
    }
}
